<template>
  <div class="fx-anchor-link" :data-id="domMarkId">
    <div class="fx-anchor-link-title text_hide" :data-id="domMarkId" :class="{active:currentCheckedId===domMarkId}"
         @click.stop="handleAnchorClick">
      {{ title }}
    </div>
    <slot/>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject, PropType, Ref, ref } from 'vue'
import { Emitter } from 'mitt'
import { randomId, scrollYAnimation } from '@/base/utils'
import { useCheckinPage } from '@/base/hooks'

interface AnchorItemProps {
  title: string;
  href: string;
}

export default defineComponent({
  name: 'fxAnchorLink',
  props: {
    title: {
      type: String as PropType<string>,
      required: true
    },
    href: {
      type: String as PropType<string>,
      required: true
    }
  },
  setup (props: AnchorItemProps) {
    const domMarkId = ref<string>(randomId(10))
    const anchorMittEmit = inject<Emitter['emit'] | undefined>('anchorMittEmit', undefined)
    const currentCheckedId = inject<Ref<string> | undefined>('currentCheckedId', undefined)
    const scrollTarget = inject<Ref<string> | undefined>('scrollTarget', undefined)
    const scrollOffset = inject<Ref<number> | undefined>('scrollOffset', undefined)

    const handleAnchorClick = () => {
      const hrefDom = document.querySelector(props.href) as HTMLElement
      if (hrefDom && scrollTarget) {
        const scrollTargetDom = document.querySelector(scrollTarget.value) as HTMLElement
        const { y } = scrollTargetDom.getBoundingClientRect()
        const offset = scrollOffset?.value || 0
        scrollYAnimation(hrefDom.offsetTop - y - offset, scrollTargetDom)
      }
      anchorMittEmit && anchorMittEmit('anchorLink', domMarkId.value)
    }

    useCheckinPage(() => {
      anchorMittEmit && anchorMittEmit('anchorLinkDom', { domId: props.href, id: domMarkId.value })
    })

    return {
      domMarkId,
      currentCheckedId,
      handleAnchorClick
    }
  }
})
</script>
